from apps.common.base.views import *
from .serializers import *
from apps.common.ali import setting
from apps.common.utils.tools import random_str
from apps.system.lessee.dao import LesseeDao
# -*- coding: utf-8 -*-

from apps.common.uploadFile.serviceOfoss import get_bucket


class FileViewOfOssSet(BaseViewSet):
    '''上传图片'''

    @action(methods=['post'], detail=False, url_path='uploadImage')
    def uploadImageAPI(self, request):
        params = getRequestParams(request)
        if not params.get('clientname'):
            return Response(response_message('终端标识必传参数'))

        fp = request.FILES.get('file')
        if not fp:
            return Response(response_error('图片为空'))
        if fp:
            fileName = random_str(8)
            if fp.size > 1024 * 1024 * 500:
                return Response(response_message('大于500M，不允许上传'))
            if fp.content_type.find('image') >= 0:
                fileType = 'image'
            elif fp.content_type.find('video') >= 0:
                fileType = 'video'
            elif fp.content_type.find('audio') >= 0:
                fileType = 'audio'
            else:
                return Response(response_message('文件格式非法'))
            # 第二道防护：判断文件后缀
            whileNames = ['.jpg', '.png', '.webp', '.gif', '.jpeg', '.JPG', '.PNG', '.GIF', '.JPEG', '.mp4', '.avi', '.wmv',
                          '.flv', '.rmvb']
            # print('fp.name[-4:-3]', fp.name[-4:-3], fp.name[-4:])
            if fp.name[-4:-3] == '.':
                fileName = fp.name[-4:]
            elif fp.name[-5:-4] == '.':
                fileName = fp.name[-5:]
            if fileName not in whileNames:
                return Response(response_message('文件格式非法'))
            # 第三道防护：修改文件名
            fileName = random_str(10) + str(request.user.id) + fileName
        else:
            return Response(response_message('文件为空'))

        # print('参数', fp, filePath, fileName, fileType, fp.size)

        imgUrl = ''
        _lessee = LesseeDao().getLessee()
        bucket_res = get_bucket()
        bucket = bucket_res.get('bucket')
        imgUrl = 'lessee' + str(_lessee.id) + '/' + params.get('clientname') + '/' + bucket_res.get('filePath') + fileName
        baseImgUrl = bucket_res.get('baseImgUrl')

        bucket.put_object(imgUrl, fp)

        # 将文件路径存到数据库
        serializers = FileSerializer(
            data={'fileName': imgUrl, 'baseImgUrl': baseImgUrl, 'fileType': fileType, 'fileSize': fp.size})
        if serializers.is_valid():
            serializers.save()
        else:
            print('file保存失败', serializers.errors)

        return Response(response_success_notScrypt({"url": baseImgUrl + imgUrl}))